import { Logger } from "./Logger";

export class BitUtil {

    //index是二进制从右到左
    public static isBitSet(value: number, index: number): boolean {
        if(isNaN(value)){
            return false
        }
        let str: string = value.toString(2);
        // Logger.log("isBitSet===", str, index);
        if (parseInt(str[str.length - 1 - index]) == 1) {
            // Logger.log("isBitSet===", str, index);
            return true
        }
        return false
    }

    //从右到左计算
    public static setBitValue(value: number, index: number): number {
        let str: string = value.toString(2);
        let strArr: Array<string> = str.split("");
        let offestLen: number = index - strArr.length + 1
        if (offestLen > 0) {
            for (let i = 0; i < offestLen; i++) {
                strArr.unshift("0")
            }
        }
        let setIndex: number = (strArr.length - index - 1)
        strArr[setIndex] = "1"

        let newStr: string = ""
        for (let i = 0; i < strArr.length; i++) {
            newStr += strArr[i]
        }
        // Logger.log("setBitValue==", str, index, newStr)
        let newValue: number = parseInt(newStr, 2);
        return newValue;
    }

    public static clearBitValue(value: number, index: number) {
        let str: string = value.toString(2);
        let newStr: string = ""
        for (let i = 0; i < str.length; i++) {
            if (i == (str.length - index - 1)) {
                newStr = newStr + "0"
            } else {
                newStr = newStr + str.charAt(i)
            }
        }
        let newValue: number = parseInt(newStr, 2);
        return newValue;
    }
}
